package com.sjgame.base.config.shiro;


import com.sjgame.base.config.redis.RedisCacheManager;
import com.sjgame.base.config.redis.RedisSessionDAO;
import com.sjgame.base.entity.Resource;
import com.sjgame.base.service.IResourceService;
import org.springframework.core.env.Environment;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * create by zcl
 */
// http://shiro.apache.org/spring-boot.html#configuration-properties
@Configuration
public class ShiroConfig {
    @javax.annotation.Resource
    private IResourceService resourceService;
    @javax.annotation.Resource
    private RedisSessionDAO sessionDAO;
    @Autowired
    private Environment env;

    @Bean
    public Realm realm() {
        return new MyRealm();
    }
    @Bean
    public RedisCacheManager redisCacheManager() {
        return new RedisCacheManager();
    }

    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();

        // logged in users with the 'admin' role
        // chainDefinition.addPathDefinition("/**", "authc, roles[admin]");

        // logged in users with the 'document:read' permission
        // chainDefinition.addPathDefinition("/docs/**", "authc, perms[document:read]");

        // all other paths require a logged in user
        // chainDefinition.addPathDefinition("/**", "authc");

        // 不需要在此处配置权限页面,因为ShiroFilterFactoryBean已经配置过,但是此处必须存在,因为shiro-spring-boot-web-starter或查找此Bean,没有会报错
        return chainDefinition;
    }

    @Bean
    public CacheManager cacheManager() {
        return new MemoryConstrainedCacheManager();
    }

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);

        shiroFilter.setLoginUrl("/login");
        shiroFilter.setSuccessUrl("/index");
        shiroFilter.setUnauthorizedUrl("/privilege/no");
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/assets/**", "anon");

        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/Kaptcha.jpg", "anon");
        filterChainDefinitionMap.put("/checkcode", "anon");
        List<Resource> list = resourceService.findAll();
        for (Resource resource : list) {
            filterChainDefinitionMap.put(resource.getSourceUrl(), "perms[" + resource.getSourceKey() + "]");
        }
        filterChainDefinitionMap.put("/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilter;
    }



//    @Bean(name = "sessionIdGenerator")
//    public JavaUuidSessionIdGenerator sessionIdGenerator() {
//        return new JavaUuidSessionIdGenerator();
//    }

//    @Bean(name = "sessionIdCookie")
//    public SimpleCookie sessionIdCookie() {
//        SimpleCookie cookie = new SimpleCookie();
//        cookie.setName("WEBSID");
//        cookie.setHttpOnly(true);
//        cookie.setMaxAge(18000);
//        return cookie;
//    }



//    @Bean(name = "sessionDao")
//    public EnterpriseCacheSessionDAO sessionDao() {
//        EnterpriseCacheSessionDAO sessionDao = new EnterpriseCacheSessionDAO();
//        sessionDao.setActiveSessionsCacheName("shiro-activeSessionCache");
//        sessionDao.setSessionIdGenerator(new JavaUuidSessionIdGenerator());
//        return sessionDao;
//    }
//

    //    @Bean(name = "lifecycleBeanPostProcessor")
//    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
//        return new LifecycleBeanPostProcessor();
//    }

//    @Bean
//    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
//        DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
//        daap.setProxyTargetClass(true);
//        return daap;
//    }
//===============================为了开发方便 注释下面两个方法  如果开启 热部署就会出问题============
    //===============================下面两个方法主要是session 共享有关 如果开启热部署就会失效============
//    @Bean(name = "sessionManager")
//    public DefaultWebSessionManager sessionManager() {
//        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
//       sessionManager.setGlobalSessionTimeout(1800000);
//        sessionManager.setDeleteInvalidSessions(true);
//        sessionManager.setSessionValidationSchedulerEnabled(true);
//        sessionManager.setSessionIdUrlRewritingEnabled(false);
//        // sessionManager.setSessionValidationScheduler(new QuartzSessionValidationScheduler());
//      // sessionManager.setSessionDAO(sessionDao());
//       // sessionManager.setSessionIdCookieEnabled(true);
//       // sessionManager.setSessionIdCookie(sessionIdCookie());
//        //----------session 共享-----------
//       if("true".equalsIgnoreCase( env.getProperty("session.gongxiang.flag"))){
//           sessionManager.setSessionDAO(sessionDAO);
//           //sessionManager.setGlobalSessionTimeout(1800);
//           sessionManager.setCacheManager(redisCacheManager());
//       }
//
//        return sessionManager;
//
//
//    }

//    @Bean(name = "securityManager")
//    public DefaultWebSecurityManager getDefaultWebSecurityManager( DefaultWebSessionManager sessionManager) {
//        DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
//        dwsm.setRealm(realm());
//        dwsm.setSessionManager(sessionManager);
//        // 用户授权/认证信息Cache, 采用EhCache 缓存
//        //dwsm.setCacheManager(redisCacheManager());
//        return dwsm;
//    }


}
